<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      title="新增销售单"
      :btnList="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :label-width="formInfo.labelWidth"
          />
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :checkBox="false"
                :tabIndex="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber || '-' }}</p>
                  <p>{{ scope.row.brandName || '-' }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.productCategoryValue || '-' }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
                <template v-slot:col-calcUnitName="scope">
                  <p>{{ scope.row.calcUnitName || '-' }}</p>
                  <p>{{ scope.row.unitConvertCoefficient || '-' }}</p>
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'change',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-refuseQty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.refuseLargeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'change',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.refuseLargeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.refuseSmallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.refuseQty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>
<script setup name="saleOrderModify">
import {
  addSaleOrder,
  updateSaleOrder,
  saleDetailBySaleId,
  getSaleDetailByPurch,
  getSaleOrderById,
} from '@/api/supplier.js'
import { getPurchOrderDetailAll } from '@/api/purch.js'

import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  pendSaleorderId: {
    type: [Number, String],
  },
  saleOrderId: {
    type: [Number, String],
  },
  purchType: {
    type: [Number, String],
  },
})

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const fullInfo = reactive({
  btnList: [{ label: '提交', event: save, show: true }],
})
let formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '采购单号',
      value: 'purchNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '客户',
      value: 'hospitalName',
      type: 'input',
      disabled: true,
    },
    {
      label: '客户部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '收货地址',
      value: 'receiveAddressValue',
      type: 'input',
      disabled: true,
    },
    {
      label: '联系人',
      value: 'receiveContacts',
      type: 'input',
      disabled: true,
    },
    {
      label: '联系电话',
      value: 'receivePhone',
      type: 'input',
      disabled: true,
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  labelWidth: '120px',
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'purchQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'refuseQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'receiveRefuseQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: 220,
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      minWidth: 150,
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '计算单位\n转换系数', value: 'calcUnitName', type: 'slot' },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '销售数量',
      value: 'purchQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '接收数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
    },
    {
      label: '拒收数量',
      value: 'refuseQty',
      type: 'slot',
      minWidth: '250px',
    },
    {
      label: '收货拒收数量',
      value: 'receiveRefuseQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
      hidden: false,
    },
    {
      label: '销售金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: 220,
    },
    {
      label: '是否寄售',
      value: 'isConsignmentValue',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
  ],
})
const formRefs = ref('')
const orgInfo = reactive({
  visible: false,
})
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let refuseSmallUnitQty = parseFloat(row.refuseSmallUnitQty || 0)
        let refuseLargeUnitQty = parseFloat(row.refuseLargeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.qtyFormatter(
          proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        )
        let refuseCalcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(refuseLargeUnitQty, unitConvertCoefficient),
          refuseSmallUnitQty
        )
        let refuseQty = proxy.$fn.qtyFormatter(
          proxy.$fn.accDiv(refuseCalcQty, unitConvertCoefficient)
        )
        let sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        row['qty'] = qty
        row['calcQty'] = calcQty
        row['refuseQty'] = refuseQty
        row['refuseCalcQty'] = refuseCalcQty
        row['sumAmount'] = sumAmount
      })
    }
  },
  {
    deep: true,
  }
)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
onMounted(() => {
  if (props.pendSaleorderId) {
    getPendMain()
  } else if (props.saleOrderId) {
    getMain()
    getList()
  }
  tableInfo.fieldList.forEach((item) => {
    if (item.value === 'receiveRefuseQty') {
      if (systemConfig.value.receive_refuse_type === 2) {
        item.hidden = false
      } else {
        item.hidden = true
      }
    }
  })
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
})

function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.purchCalcQty / row.unitConvertCoefficient)
  } else {
    return row.purchQty
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let itemList = tableInfo.data
      .filter(
        (item) =>
          item.purchCalcQty !==
          proxy.$fn.qtyFormatter(
            proxy.$fn.accAdd(item.calcQty, item.refuseCalcQty)
          )
      )
      .map((item) => item.commonName)
    if (itemList.length) {
      proxy.$alert(
        `产品【${itemList}】的接收数量与拒绝数量之和不等于销售数量！`,
        '操作提示',
        {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
        }
      )
      return
    }
    formInfo = {
      ...formInfo.data,
      details: proxy.$fn.filterBlacklist(tableInfo.data),
    }
    let api = ''
    if (props.pendSaleorderId) {
      api = addSaleOrder
    } else if (props.saleOrderId) {
      api = updateSaleOrder
    }
    api(formInfo).then((resp) => {
      if (resp && resp.success) {
        emit('returnModify')
        showDialog.value = false
      }
    })
  })
}
function openDeptWindow() {
  orgInfo.visible = true
}
function reset() {
  orgInfo.visible = false
}
function getPurchOrderDetailAllList(orderId) {
  getPurchOrderDetailAll({ purchOrderId: orderId }).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}
function getPendMain() {
  let param = {
    id: props.pendSaleorderId,
    purchType: props.purchType,
  }
  getSaleDetailByPurch(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      if (data.details.length) {
        data.details.forEach((row) => {
          if (row.qtyOperateMode === 2) {
            row.largeUnitQty = parseInt(
              row.purchCalcQty / row.unitConvertCoefficient
            )
            row.smallUnitQty = parseInt(
              row.purchCalcQty % row.unitConvertCoefficient
            )
          } else {
            row.largeUnitQty = row.purchQty
            row.smallUnitQty = 0
          }
          row.refuseSmallUnitQty = 0
          row.refuseLargeUnitQty = 0
        })
      }
      tableInfo.data = data.details
      formInfo.data = res.data
    }
  })
}
function getMain() {
  getSaleOrderById(props.saleOrderId).then((res) => {
    if (res && res.success) {
      formInfo.data = res.data
    }
  })
}
function getList() {
  saleDetailBySaleId({ orderId: props.saleOrderId }).then((res) => {
    if (res && res.success) {
      tableInfo.data = res.data
    }
  })
}
</script>
